<template>
  <van-popup v-model:show="showBottom" position="bottom" round :style="{ height: '80%' }">
    <div class="flex flex-col h-full">
      <h2 class="font-bold my-3 text-center">选择商机</h2>
      <div class="flex flex-row items-center justify-between px-3 pb-4">
        <div class="flex-auto">
          <van-search
            v-model="searchValue"
            shape="round"
            placeholder="请输入商机名称"
            input-align="center"
            @update:model-value="(v) => debounce(() => onSearch(v))"
            @search="onSearch"
          >
            <template #action>
              <div @click="onClickButton">搜索</div>
            </template>
          </van-search>
        </div>
      </div>

      <div class="flex-auto overflow-y-auto">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
            v-model:loading="loading"
            :finished="finished"
            :immediate-chec="false"
            :offset="50"
            finished-text="没有更多了"
            @load="loadMoreData"
          >
            <van-cell v-for="item in list" :key="item">
              <div
                class="flex flex-row items-center justify-between text-left gap-1 h-full py-2"
              >
                <div
                  class="flex-auto flex flex-row items-center box-border"
                  @click="onSelectBox(item)"
                >
                  <img
                    v-if="item.selected"
                    src="../../icons/svg/orderVisit/checked_icon.svg"
                    alt="选中"
                  />
                  <img
                    v-else
                    src="../../icons/svg/orderVisit/uncheck_icon.svg"
                    alt="未选"
                  />
                  <div class="ml-2 flex-auto">
                    <van-text-ellipsis
                      class="text-[#262626] text-[16px] font-medium"
                      :content="item.name"
                    />
                    <p class="text-[#8C8C8C] text-[12px] truncate">
                      {{ getDes(item) }}
                    </p>
                  </div>
                </div>

                <div
                  v-if="item.formFieldValues && item.formFieldValues.length > 0"
                  class="w-[44px] h-[44px] flex justify-center items-center"
                  @click="showDetailFun(item)"
                >
                  <van-icon name="arrow"></van-icon>
                </div>
              </div>
            </van-cell>
          </van-list>
        </van-pull-refresh>
      </div>

      <div class="px-4 pb-8 pt-1">
        <van-button
          size="large"
          :disabled="selectCount === 0"
          round
          color="#436BFF"
          @click="onConfirm"
          >确定</van-button
        >
      </div>
    </div>
  </van-popup>

  <editCustomerView ref="editCustomerRef" @create-success="onRefresh" />

  <van-popup v-model:show="showDetail" round>
    <div class="rounded-md flex flex-col w-[320px] px-10 py-6">
      <div class="w-full font-bold text-center mb-4">{{ itemDetail.name }}</div>
      <template class="mb-3" v-for="item in getDetail(itemDetail)" :key="item">
        <div class="mb-2">
          <p class="font-medium mr-2 text-yxt-grey-800">{{ item.title }} :</p>
          <p class="text-[#8C8C8C] text-sm">{{ item.value || "-" }}</p>
        </div>
      </template>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, defineExpose, onMounted, computed, defineEmits } from "vue";
import { opportunityListAPI } from "@/services/myXmate";
import { useCommonStore } from "@/store";
import editCustomerView from "./editBusinessOpportunityView.vue";
import debounce from "@/utils/debounce";

const emits = defineEmits(["onConfirm"]);

const commonStore = useCommonStore();

onMounted(() => {
  commonStore.searchCustomerTypeAction();
  onRefresh();
});

const customerList = computed(() => commonStore.enableCreateCustomerArr);

function onSelectBox(v) {
  list.value.forEach((value) => (value.selected = false));
  v.selected = true;
}

const selectArray = computed(() => list.value.filter((v) => v.selected));
const selectCount = computed(() => selectArray.length);

// 列表相关
const searchValue = ref("");
const list = ref([]);
const loading = ref(false);
const refreshing = ref(false);
const finished = ref(false);
const totalNum = ref(0);

function getDes(item) {
  return "关联客户:" + (item.customerName || "-");
}

function getDetail(item) {
  const { formFieldValues } = item;
  if (!formFieldValues) {
    return "";
  }
  let tempArr = formFieldValues.map((v) => {
    return {
      title: v.fieldName,
      value: v.fieldValue || "-",
    };
  });
  // 插入数组索引为0的位置
  tempArr.unshift({
    title: "关联客户",
    value: item.customerName || "-",
  });
  return tempArr;
}

const showDetail = ref(false);
const itemDetail = ref(null);

function showDetailFun(item) {
  console.log(item);
  showDetail.value = true;
  itemDetail.value = item;
}

async function onRefresh() {
  refreshing.value = true;
  page.value = 1;
  await loadData();
  refreshing.value = false;
}

function onSearch() {
  loadData();
}

const page = ref(1);
const pageSize = ref(30);
function loadMoreData() {
  page.value++;
  loadData();
}

async function loadData() {
  loading.value = true;
  const { datas, totalNum: totals } = await opportunityListAPI({
    searchKey: searchValue.value,
    pageNumber: page.value,
    pageSize: pageSize.value,
  });

  console.log("datas: ", datas.length, pageSize.value);
  if (datas.length < pageSize.value) {
    finished.value = true;
  }
  if (page.value === 1) {
    list.value = datas;
  } else {
    list.value = [...list.value, ...datas];
  }

  totalNum.value = totals;
  loading.value = false;
}

function onConfirm() {
  if (selectArray.value.length === 0) {
    return;
  }
  emits("onConfirm", selectArray.value[0]);
  hidden();
}

//创建商机相关
const editCustomerRef = ref();
const selectCustomerTypeRef = ref(null);

// 控制显示隐藏相关
const showBottom = ref(false);

function show() {
  showBottom.value = true;
}

function hidden() {
  showBottom.value = false;
}

defineExpose({
  show,
  hidden,
});
</script>

<style scoped lang="less">
.text-\[\#8C8C8C\].text-\[12px\] {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
